#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import os,subprocess

server = socket.socket() #获得socket实例
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

server.bind(("127.0.0.1",8000)) #绑定ip port
server.listen()  #开始监听

while True:#第一层loop
    conn,addr = server.accept()#接受并建立与客户端的连接,程序在此处开始阻塞,只到有客户端连接进来...
    while True:
        try:
            data = conn.recv(1024)
        except Exception:
            break

        if not data:break
        print('......',str(data,'utf8'))

        cmd_result = subprocess.Popen(data.decode('utf8'),shell=True,stdout=subprocess.PIPE).stdout.read()

        #len(cmd_result)是int类型，int不能转为bytes类型，需要str后才能转成utf8的bytes类型
        #str(data,'utf8') == data.decode('utf8') 都是转为utf8的bytes（16精制的字节）类型
        result_len = bytes(str(len(cmd_result)),'utf8')
        print('>>>',result_len)
        conn.sendall(result_len)

        #两个send在一起容易产生粘包 解决办法
        conn.recv(1024)

        conn.sendall(cmd_result)
server.close()